package com.xhj.myframe.myspring.aop.aspectJ;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Random;
/**
 * -
 *
 * @author 见见 pure_xhj@163.com @Date 2021-08-22 @Time 14:00
 */
@Aspect
@Component
public class Log {

  @Autowired MyCatch myCatch;

  @Pointcut("execution(* com.xhj.myframe.myspring.aop.aspectJ.Calculation.*(..))")
  public void point() {}

  @Before("point()")
  public void before(JoinPoint joinPoint) {
    // 判断
    if (Integer.valueOf((String) joinPoint.getArgs()[0]) != 1) {
      while (myCatch.flag != 0) {}
    }
    // 干活
    myCatch.flag = 1;
    myCatch.add();
    System.out.println("myCatch.num = " + myCatch.num + " , myCatch.i = " + myCatch.i);
    System.out.println(Thread.currentThread().getName() + ": myCatch.flag = " + myCatch.flag);
    System.out.println(Thread.currentThread().getName() + ": come in before...");
    Object[] args = joinPoint.getArgs();
    String accountId = (String) args[0];
    Random random = new Random();
    int nextInt = random.nextInt(1000);
    //    try {Thread.sleep(nextInt);} catch (InterruptedException e) {e.printStackTrace();}
    System.out.println(
        Thread.currentThread().getName() + ": " + "accountId:" + accountId + " time:" + nextInt);
    // 通知
    System.out.println(Thread.currentThread().getName() + ": leave...\n");
    myCatch.flag = 0;
  }

  @After("point()")
  public void after() {
    System.out.println("after...");
  }

  @AfterThrowing("point()")
  public void afterThrowing() {
    System.out.println("afterThrowing...");
  }

  @AfterReturning("point()")
  public void afterReturning() {
    System.out.println("afterReturning...");
  }

  @Around("point()")
  public int around(ProceedingJoinPoint pjp) throws Throwable {
    System.out.println("around start...");
    Object proceed = pjp.proceed();
    System.out.println("around end...");
    return 0;
  }
}
